import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'index.dart';
import '../../../common/models/index.dart'; // 添加models导入以使用ApiShortVideoDto

/// 我的页面视图 - 紧凑优化版
class MyIndexPage extends GetView<MyIndexController> {
  const MyIndexPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return CustomScrollView(
      controller: controller.scrollController,
      slivers: [
        // 顶部用户信息卡片
        _buildUserHeader(),
        
        // 白色内容区域（统计数据 + 个性签名 + 广告横幅 + 功能菜单）
        _buildContentCard(),
        
        // Tab标签栏
        _buildTabBar(),
        
        // Tab内容
        _buildTabContent(),
      ],
    );
  }

  // 构建用户头部卡片（紧凑优化 - 使用本地背景图）
  Widget _buildUserHeader() {
    return SliverToBoxAdapter(
      child: Container(
        height: 221.h, // 匹配Android的221.5dp
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/me_top_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 毛玻璃效果背景
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withOpacity(0.1),
                    Colors.black.withOpacity(0.3),
                  ],
                ),
              ),
            ),
            
            // 内容
            Padding(
              padding: EdgeInsets.only(
                top: MediaQuery.of(Get.context!).padding.top + 44.h + 12.h, // 匹配新的AppBar高度
                left: 16.w,
                right: 16.w,
                bottom: 16.h,
              ),
              child: Row(
                children: [
                  // 头像（紧凑）
                  GestureDetector(
                    onTap: controller.onAvatarTap,
                    child: Hero(
                      tag: 'user_avatar',
                      child: Container(
                        width: 70.w,  // 更接近Android的80dp
                        height: 70.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(
                            color: Colors.white,
                            width: 2.5,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3),
                              blurRadius: 8.r,
                              spreadRadius: 1,
                            ),
                          ],
                        ),
                        child: ClipOval(
                          child: controller.userAvatarUrl.isNotEmpty
                              ? Image.network(
                                  controller.userAvatarUrl,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) => _buildDefaultAvatar(),
                                )
                              : _buildDefaultAvatar(),
                        ),
                      ),
                    ),
                  ),
                  
                  SizedBox(width: 12.w), // 16 → 12
                  
                  // 用户信息
                  Expanded(
                    child: Obx(() {
                      final username = controller.myHeadInfo.value?.userInfo.username ?? controller.userDisplayName;
                      final userId = controller.myHeadInfo.value?.userInfo.userId.toString() ?? controller.userId;
                      
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          GestureDetector(
                            onTap: controller.onUserNameTap,
                            child: Text(
                              username,
                              style: TextStyle(
                                fontSize: 18.sp, // 20 → 18 (一级标题标准)
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                                shadows: [
                                  Shadow(
                                    color: Colors.black.withOpacity(0.5),
                                    blurRadius: 4.r,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(height: 3.h), // 4 → 3
                          Text(
                            'ID: ${userId.isNotEmpty ? userId : "未设置"}',
                            style: TextStyle(
                              fontSize: 11.sp, // 13 → 11 (辅助文本标准)
                              color: Colors.white.withOpacity(0.9),
                              shadows: [
                                Shadow(
                                  color: Colors.black.withOpacity(0.5),
                                  blurRadius: 4.r,
                                ),
                              ],
                            ),
                          ),
                        ],
                      );
                    }),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建默认头像
  Widget _buildDefaultAvatar() {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: RadialGradient(
          colors: [
            Colors.grey.shade300,
            Colors.grey.shade500,
          ],
        ),
      ),
      child: Icon(
        Icons.person,
        size: 30.r, // 35 → 30
        color: Colors.white,
      ),
    );
  }

  // 构建白色内容卡片（包含：统计数据 + 个性签名 + 广告横幅 + 功能菜单）
  // 对应 Android 的 ll_collapsible_content
  Widget _buildContentCard() {
    final menuItems = [
      {'iconPath': 'assets/icons/icon_wallet_black.png', 'label': '我的零钱', 'color': const Color(0xFFFF6B6B)},
      {'iconPath': 'assets/icons/icon_my_sharing.png', 'label': '我的分享', 'color': const Color(0xFF6B5EFF)},
      {'iconPath': 'assets/icons/icon_team_black.png', 'label': '组队大厅', 'color': const Color(0xFF5EB3FF)},
      {'iconPath': 'assets/icons/icon_task_black.png', 'label': '我的任务', 'color': const Color(0xFFFF8C5E)},
      {'iconPath': 'assets/icons/icon_task_my_back.png', 'label': '广告主', 'color': const Color(0xFFFFB05E)},
      {'iconPath': 'assets/icons/icon_guild_black.png', 'label': '领主管理', 'color': const Color(0xFF9B5EFF)},
    ];
    
    return SliverToBoxAdapter(
      child: Container(
        decoration: BoxDecoration(
        color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(15.r)), // 顶部圆角
        ),
        padding: EdgeInsets.only(top: 16.h), // 优化上边距：22→16（标准间距）
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 1. 统计数据区域（移入白色容器内）
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 0), // 屏幕宽度的3%
        child: Obx(() {
          final headInfo = controller.myHeadInfo.value;
          
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatItem(
                headInfo?.giveMeRewardNum.toString() ?? '0', 
                '打赏'
              ),
                    _buildStatDivider(), // 分隔线
              _buildStatItem(
                headInfo?.mutualFollowNum.toString() ?? '0', 
                '互关'
              ),
                    _buildStatDivider(), // 分隔线
              _buildStatItem(
                headInfo?.followNum.toString() ?? '0', 
                '关注'
              ),
                    _buildStatDivider(), // 分隔线
              _buildStatItem(
                headInfo?.fansNum.toString() ?? '0', 
                '粉丝'
              ),
            ],
          );
        }),
      ),
            
            // 2. 个性签名
            Container(
              padding: EdgeInsets.fromLTRB(1.sw * 0.03, 20.h, 1.sw * 0.03, 0), // 左右边距：屏幕宽度的3%
        child: Obx(() {
          final signature = controller.myHeadInfo.value?.userInfo.signature;
          
          return Text(
            signature?.isNotEmpty == true 
                ? signature! 
                : '这个家伙很懒，什么也没说...',
            style: TextStyle(
                    fontSize: 12.sp, // 正文标准：12sp
                    color: const Color(0xFF7C7C7C),
            ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
          );
        }),
      ),
            
            // 3. 推广横幅
            Container(
              margin: EdgeInsets.fromLTRB(1.sw * 0.03, 8.h, 1.sw * 0.03, 12.h), // 左右边距：屏幕宽度的3%
              width: double.infinity,
              height: 74.h,
              child: Image.asset(
                'assets/images/icon_commission_bg.png',
                fit: BoxFit.fill,
              ),
            ),
            
            // 4. 功能菜单
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 0), // 屏幕宽度的3%
              child: Column(
                children: [
                  // 第一行：4个，均匀分布
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildMenuItem(iconPath: menuItems[0]['iconPath'] as String, label: menuItems[0]['label'] as String, color: menuItems[0]['color'] as Color, onTap: () {}),
                      _buildMenuItem(iconPath: menuItems[1]['iconPath'] as String, label: menuItems[1]['label'] as String, color: menuItems[1]['color'] as Color, onTap: () {}),
                      _buildMenuItem(iconPath: menuItems[2]['iconPath'] as String, label: menuItems[2]['label'] as String, color: menuItems[2]['color'] as Color, onTap: () {}),
                      _buildMenuItem(iconPath: menuItems[3]['iconPath'] as String, label: menuItems[3]['label'] as String, color: menuItems[3]['color'] as Color, onTap: () {}),
                    ],
                  ),
                  SizedBox(height: 8.h), // 优化间距：10→8
                  // 第二行：2个可见 + 2个不可见占位（匹配Android布局）
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      _buildMenuItem(iconPath: menuItems[4]['iconPath'] as String, label: menuItems[4]['label'] as String, color: menuItems[4]['color'] as Color, onTap: () {}),
                      Expanded(child: SizedBox()), // layout_weight="1"
                      _buildMenuItem(iconPath: menuItems[5]['iconPath'] as String, label: menuItems[5]['label'] as String, color: menuItems[5]['color'] as Color, onTap: () {}),
                      Expanded(child: SizedBox()), // layout_weight="1"
                      SizedBox(width: 60.w), // 不可见的第3个按钮位置
                      Expanded(child: SizedBox()), // layout_weight="1"
                      SizedBox(width: 60.w), // 不可见的第4个按钮位置
                    ],
                  ),
                  SizedBox(height: 12.h), // 优化底部间距：16→12
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建统计项（匹配Android样式）
  Widget _buildStatItem(String value, String label) {
    return Column(
      mainAxisSize: MainAxisSize.min,
          children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 17.sp, // Android: 17sp
            fontWeight: FontWeight.bold,
            color: const Color(0xFF1C1C1C), // Android: @color/color_1C1C1C
          ),
        ),
        SizedBox(height: 6.h), // 优化间距
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp, // 正文标准：12sp
            color: const Color(0xFF666666),
          ),
        ),
      ],
    );
  }

  // 构建统计数据分隔线（匹配Android样式）
  Widget _buildStatDivider() {
    return Container(
      width: 0.75.w, // Android: 0.75dp
      height: 20.h,  // Android: 20dp
      color: const Color(0x307C7C7C), // Android: #307C7C7C（透明度30%）
    );
  }

  // 构建菜单项（固定宽度60dp，匹配Android）
  Widget _buildMenuItem({
    required String iconPath,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: SizedBox(
        width: 60.w, // Android: 60dp固定宽度
      child: Column(
          mainAxisSize: MainAxisSize.min,
        children: [
            // 图标（Android: 37.5dp x 43dp）
            Image.asset(
              iconPath,
              width: 37.5.w,  // 匹配Android尺寸
              height: 43.h,
              fit: BoxFit.contain,
            ),
            SizedBox(height: 4.h), // 优化间距：2→4
          // 文本
          Text(
            label,
            style: TextStyle(
                fontSize: 13.sp, // 恢复字体大小：11→13
                color: Colors.black,
              height: 1.0,
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
        ),
      ),
    );
  }

  // 构建Tab栏（完全重构 - 优化吸顶效果）
  Widget _buildTabBar() {
    final tabHeight = 48.h; // 统一Tab高度
    
    return SliverPersistentHeader(
      pinned: true, // ✅ 固定在顶部（AppBar下方）
      delegate: _StickyTabBarDelegate(
        height: tabHeight, // ✅ 明确传递高度参数
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03), // 统一边距：屏幕宽度的3%
          child: Obx(() => Row(
            children: [
              _buildTabItem('喜欢', 0),
              _buildTabItem('推荐', 1),
              _buildTabItem('历史', 2),
              _buildTabItem('收藏', 3),
            ],
          )),
        ),
      ),
    );
  }

  // 构建Tab项（优化版 - 短指示器 + 全部粗体）
  Widget _buildTabItem(String label, int index) {
    final isActive = controller.currentTabIndex.value == index;
    
    return Expanded(
      child: GestureDetector(
        onTap: () => controller.onTabTap(index),
        behavior: HitTestBehavior.opaque,
        child: Container(
          height: 48.h,
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 文字（全部粗体）
              Text(
                label,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.bold, // 统一使用粗体
                  color: isActive ? const Color(0xFF1D1D1F) : const Color(0xFF999999),
                ),
              ),
              SizedBox(height: 6.h),
              // 短指示器（仅选中时显示）
              Container(
                width: 24.w, // 指示器宽度：24px（短一点）
                height: 3.h,  // 指示器高度：3px
                decoration: BoxDecoration(
                  color: isActive ? const Color(0xFFFF6B35) : Colors.transparent,
                  borderRadius: BorderRadius.circular(1.5.r), // 圆角
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建Tab内容（根据选中的Tab显示不同内容）
  Widget _buildTabContent() {
    return Obx(() {
      switch (controller.currentTabIndex.value) {
        case 0:
          return _buildLikesContent();
        case 1:
          return _buildRecommendContent();
        case 2:
          return _buildHistoryContent();
        case 3:
          return _buildCollectionContent();
        default:
          return _buildLikesContent();
      }
    });
  }

  // 喜欢内容（网格布局显示短视频）
  Widget _buildLikesContent() {
    return Obx(() {
      // 如果正在加载且列表为空，显示加载指示器
      if (controller.likesLoading.value && controller.likesVideos.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 300.h,
            color: const Color(0xFFF5F5F5),
            child: const Center(
              child: CircularProgressIndicator(),
            ),
          ),
        );
      }
      
      // 如果列表为空，显示空状态
      if (controller.likesVideos.isEmpty) {
    return SliverToBoxAdapter(
      child: Container(
        height: 300.h,
        color: const Color(0xFFF5F5F5),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                'assets/images/img_work_empty.png',
                    width: 120.w,
                    height: 120.h,
                fit: BoxFit.contain,
              ),
                  SizedBox(height: 12.h),
              Text(
                '暂无喜欢记录',
                style: TextStyle(
                      fontSize: 12.sp,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

      // 显示网格布局
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 12.h),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, // 3列网格
            crossAxisSpacing: 4.w,
            mainAxisSpacing: 4.h,
            childAspectRatio: 0.75, // 宽高比
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              if (index < controller.likesVideos.length) {
                return _buildVideoGridItem(controller.likesVideos[index], 0);
              } else {
                // 加载更多指示器
                return _buildLoadMoreIndicator(controller.likesLoading.value);
              }
            },
            childCount: controller.likesVideos.length + 
                (controller.likesHasMore.value ? 1 : 0),
          ),
        ),
      );
    });
  }

  // 推荐内容（网格布局显示短视频）
  Widget _buildRecommendContent() {
    return Obx(() {
      if (controller.recommendLoading.value && controller.recommendVideos.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 300.h,
            color: const Color(0xFFF5F5F5),
            child: const Center(child: CircularProgressIndicator()),
          ),
        );
      }
      
      if (controller.recommendVideos.isEmpty) {
    return SliverToBoxAdapter(
      child: Container(
        height: 300.h,
        color: const Color(0xFFF5F5F5),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
                  Image.asset('assets/images/img_tj_empty.png', width: 120.w, height: 120.h),
                  SizedBox(height: 12.h),
                  Text('暂无推荐', style: TextStyle(fontSize: 12.sp, color: Colors.grey[600])),
                ],
                ),
              ),
          ),
        );
      }
      
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 12.h),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 4.w,
            mainAxisSpacing: 4.h,
            childAspectRatio: 0.75,
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              if (index < controller.recommendVideos.length) {
                return _buildVideoGridItem(controller.recommendVideos[index], 1);
              } else {
                return _buildLoadMoreIndicator(controller.recommendLoading.value);
              }
            },
            childCount: controller.recommendVideos.length + 
                (controller.recommendHasMore.value ? 1 : 0),
        ),
      ),
    );
    });
  }

  // 收藏内容（网格布局显示短视频）
  Widget _buildCollectionContent() {
    return Obx(() {
      if (controller.collectionLoading.value && controller.collectionVideos.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 300.h,
            color: const Color(0xFFF5F5F5),
            child: const Center(child: CircularProgressIndicator()),
          ),
        );
      }
      
      if (controller.collectionVideos.isEmpty) {
    return SliverToBoxAdapter(
      child: Container(
        height: 300.h,
        color: const Color(0xFFF5F5F5),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
                  Image.asset('assets/images/img_peivate_empty.png', width: 120.w, height: 120.h),
                  SizedBox(height: 12.h),
                  Text('暂无收藏记录', style: TextStyle(fontSize: 12.sp, color: Colors.grey[600])),
                ],
                ),
              ),
          ),
        );
      }
      
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 12.h),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 4.w,
            mainAxisSpacing: 4.h,
            childAspectRatio: 0.75,
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              if (index < controller.collectionVideos.length) {
                return _buildVideoGridItem(controller.collectionVideos[index], 3);
              } else {
                return _buildLoadMoreIndicator(controller.collectionLoading.value);
              }
            },
            childCount: controller.collectionVideos.length + 
                (controller.collectionHasMore.value ? 1 : 0),
        ),
      ),
    );
    });
  }

  // 历史记录（网格布局显示短视频）
  Widget _buildHistoryContent() {
    return Obx(() {
      if (controller.historyLoading.value && controller.historyVideos.isEmpty) {
        return SliverToBoxAdapter(
          child: Container(
            height: 300.h,
            color: const Color(0xFFF5F5F5),
            child: const Center(child: CircularProgressIndicator()),
          ),
        );
      }
      
      if (controller.historyVideos.isEmpty) {
    return SliverToBoxAdapter(
      child: Container(
        height: 300.h,
        color: const Color(0xFFF5F5F5),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
                  Image.asset('assets/images/img_history_empty.png', width: 120.w, height: 120.h),
                  SizedBox(height: 12.h),
                  Text('暂无历史记录', style: TextStyle(fontSize: 12.sp, color: Colors.grey[600])),
                ],
                ),
              ),
          ),
        );
      }
      
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 1.sw * 0.03, vertical: 12.h),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 4.w,
            mainAxisSpacing: 4.h,
            childAspectRatio: 0.75,
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              if (index < controller.historyVideos.length) {
                return _buildVideoGridItem(controller.historyVideos[index], 2);
              } else {
                return _buildLoadMoreIndicator(controller.historyLoading.value);
              }
            },
            childCount: controller.historyVideos.length + 
                (controller.historyHasMore.value ? 1 : 0),
        ),
      ),
    );
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MyIndexController>(
      // ❌ 不要在这里初始化Controller！
      // Controller应该由Binding统一管理，否则会导致重复初始化和请求重复发送
      // init: MyIndexController(),
      id: "my_index",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF5F5F5),
          extendBodyBehindAppBar: true,
          appBar: _buildAppBar(),
          body: _buildView(),
        );
      },
    );
  }
  
  /// 构建动态AppBar（根据滚动位置实时变化 + 显示头像）
  PreferredSizeWidget _buildAppBar() {
    return PreferredSize(
      preferredSize: Size.fromHeight(44.h), // 缩小AppBar高度：56→44
      child: Obx(() {
        // 获取当前透明度
        final opacity = controller.appBarOpacity.value;
        
        // 根据透明度决定状态栏图标颜色
        final statusBarIconBrightness = opacity < 0.5 
            ? Brightness.light 
            : Brightness.dark;
        
        return AppBar(
          backgroundColor: Colors.white.withOpacity(opacity),
          elevation: opacity > 0.5 ? 1 : 0,
          centerTitle: true,
          systemOverlayStyle: SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
            statusBarIconBrightness: statusBarIconBrightness,
            statusBarBrightness: statusBarIconBrightness == Brightness.light 
                ? Brightness.dark 
                : Brightness.light,
          ),
          // 动态显示标题（包含头像）
          title: AnimatedOpacity(
            opacity: controller.showAppBarTitle.value ? 1.0 : 0.0,
            duration: const Duration(milliseconds: 200),
            child: GestureDetector(
              onTap: controller.onAvatarTap,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 头像（仅在显示标题时显示）
                  if (controller.showAppBarTitle.value) ...[
                    Container(
                      width: 32.w,
                      height: 32.h,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: opacity < 0.5 
                              ? Colors.white.withOpacity(0.5)
                              : Colors.blue.shade200,
                          width: 2,
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4.r,
                            spreadRadius: 0.5,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child: controller.userAvatarUrl.isNotEmpty
                            ? Image.network(
                                controller.userAvatarUrl,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) => _buildDefaultAvatarSmall(),
                              )
                            : _buildDefaultAvatarSmall(),
                      ),
                    ),
                    SizedBox(width: 8.w),
                  ],
                  // 用户名（优先使用myHeadInfo的username）
                  Text(
                    controller.myHeadInfo.value?.userInfo.username ?? controller.userDisplayName,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF1D1D1F),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 右侧设置按钮（无背景，小尺寸，上滑渐变消失）
          actions: [
            Opacity(
              opacity: 1.0 - opacity, // 滚动时透明度从1渐变到0（消失）
              child: GestureDetector(
                onTap: controller.onSettingsTap,
                behavior: HitTestBehavior.opaque, // 扩大点击区域
                child: Padding(
                  padding: EdgeInsets.only(right: 12.w, left: 8.w), // 减小padding，让图片有更多显示空间
                  child: Image.asset(
                  'assets/icons/icon_settings.png',
                    width: 28.r,  // 进一步放大
                    height: 28.r,
                    fit: BoxFit.cover, // 使用cover让图片填充整个区域
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }
  
  /// 构建小号默认头像
  Widget _buildDefaultAvatarSmall() {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: RadialGradient(
          colors: [
            Colors.grey.shade300,
            Colors.grey.shade500,
          ],
        ),
      ),
      child: Icon(
        Icons.person,
        size: 18.r,
        color: Colors.white,
      ),
    );
  }
  
  /// 构建视频网格项
  Widget _buildVideoGridItem(ApiShortVideoDto video, int tabIndex) {
    return GestureDetector(
      onTap: () {
        // TODO: 跳转到视频详情页
        debugPrint('点击视频: ${video.shortVideoId}');
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Stack(
          fit: StackFit.expand,
          children: [
            // 封面图
            ClipRRect(
              borderRadius: BorderRadius.circular(8.r),
              child: video.thumb != null && video.thumb!.isNotEmpty
                  ? Image.network(
                      video.thumb!,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          color: Colors.grey[200],
                          child: Icon(
                            Icons.video_library,
                            size: 40.r,
                            color: Colors.grey[400],
                          ),
                        );
                      },
                    )
                  : Container(
                      color: Colors.grey[200],
                      child: Icon(
                        Icons.video_library,
                        size: 40.r,
                        color: Colors.grey[400],
                      ),
                    ),
            ),
            
            // 渐变遮罩（底部）
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                height: 60.h,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.vertical(bottom: Radius.circular(8.r)),
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.transparent,
                      Colors.black.withOpacity(0.7),
                    ],
                  ),
                ),
              ),
            ),
            
            // 视频时长标签（右下角）
            if (video.videoTime > 0)
              Positioned(
                right: 6.w,
                bottom: 6.h,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.6),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    video.formattedDuration,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            
            // 播放量（左下角）
            Positioned(
              left: 6.w,
              bottom: 6.h,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.play_arrow,
                    color: Colors.white,
                    size: 14.r,
                  ),
                  SizedBox(width: 2.w),
                  Text(
                    video.formattedViewNum,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w500,
                      shadows: [
                        Shadow(
                          color: Colors.black.withOpacity(0.5),
                          blurRadius: 2,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            
            // 点赞图标（右上角）
            Positioned(
              right: 6.w,
              top: 6.h,
              child: GestureDetector(
                onTap: () {
                  controller.toggleVideoLike(video, tabIndex);
                },
                child: Container(
                  padding: EdgeInsets.all(4.r),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.3),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    video.liked ? Icons.favorite : Icons.favorite_border,
                    color: video.liked ? Colors.red : Colors.white,
                    size: 16.r,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 构建加载更多指示器
  Widget _buildLoadMoreIndicator(bool isLoading) {
    return Container(
      alignment: Alignment.center,
      child: isLoading
          ? SizedBox(
              width: 20.r,
              height: 20.r,
              child: const CircularProgressIndicator(strokeWidth: 2),
            )
          : const SizedBox.shrink(),
    );
  }
}

/// TabBar 吸顶效果 Delegate（优化版）
/// 
/// 实现 SliverPersistentHeaderDelegate 接口，用于创建固定在顶部的 TabBar
/// 
/// 特性：
/// - 固定高度：明确指定高度避免布局问题
/// - 吸顶效果：滚动时固定在 AppBar 下方
/// - 响应式：支持屏幕适配
/// 
/// 关键优化点：
/// 1. maxExtent 和 minExtent 必须完全一致
/// 2. child 的实际渲染高度必须与 extent 一致
/// 3. 使用 SizedBox 强制约束子组件高度
class _StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;
  
  _StickyTabBarDelegate({
    required this.child,
    required this.height,
  });

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return SizedBox(
      height: height,
      child: child,
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant _StickyTabBarDelegate oldDelegate) {
    return child != oldDelegate.child || height != oldDelegate.height;
  }
}
